package com.xw.bo.ks.generator;

import com.google.common.base.CaseFormat;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TableMetadata {
    public static List<Map<String, String>> getTableMetadata(String tableName) throws SQLException {
        List<Map<String, String>> fields = new ArrayList<>();

        try (Connection connection = DatabaseUtils.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet columns = metaData.getColumns(null, null, tableName, null);
            // 驼峰转下划线
//            String resultStr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "user_name");
            // 下划线转驼峰命名
//            String resultStr = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "userName");

            while (columns.next()) {
                Map<String, String> field = new HashMap<>();
                field.put("name", CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columns.getString("COLUMN_NAME")));
                field.put("tableColumnName", columns.getString("COLUMN_NAME"));
                field.put("type", convertSqlTypeToJavaType(columns.getString("TYPE_NAME")));
                field.put("sType", convertSqlTypeToSType(columns.getString("TYPE_NAME")));
                field.put("remarks", columns.getString("REMARKS"));
                fields.add(field);
            }
        }

        return fields;
    }

    private static String convertSqlTypeToJavaType(String sqlType) {
        switch (sqlType.toUpperCase().replace("UNSIGNED", "").trim()) {
            case "VARCHAR":
            case "CHAR":
            case "TEXT":
                return "String";
            case "TINYINT":
                return "Byte";
            case "SMALLINT":
            case "INT":
            case "INTEGER":
                return "Integer";
            case "BIGINT":
                return "Long";
            case "DOUBLE":
                return "Double";
            case "DECIMAL":
                return "BigDecimal";
            case "DATE":
                return "Date";
            case "TIMESTAMP":
                return "Timestamp";
            default:
                return "String";
        }
    }

    private static String convertSqlTypeToSType(String sqlType) {
        switch (sqlType.toUpperCase().replace("UNSIGNED", "").trim()) {
            case "JSON":
                return "2";
            case "TINYINT":
                return "3";
            default:
                return "1";
        }
    }

}

